<template>
  <div class="data-display">
    <LoadingWrapper :loading="loading">
      <!-- 顶部数据卡片 -->
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in dataCards" :key="index">
          <el-card class="data-card">
            <div class="card-content">
              <div class="card-title">{{ item.title }}</div>
              <div class="card-value" :style="{ color: item.color }">{{ item.value }}</div>
              <div class="card-sub-title">{{ item.subTitle }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <!-- 热门书籍排行 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">热门书籍互动排行</div>
            </template>
            <div ref="hotBooksChartRef" class="chart"></div>
          </el-card>
        </el-col>
        
        <!-- 活跃用户排行 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">活跃用户排行</div>
            </template>
            <div ref="activeUsersChartRef" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
    </LoadingWrapper>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { getStatistics } from '@/api/statistics'
import * as echarts from 'echarts'  // 改用完整版本
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'
import { ElMessage } from 'element-plus'

// refs for charts
const hotBooksChartRef = ref(null)
const activeUsersChartRef = ref(null)
const dataCards = ref([])
const loading = ref(true)

// 统计数据
const statistics = ref({
  users: {},
  books: {},
  interactions: {},
  hotBooks: [],
  activeUsers: [],
  tags: {}
})

// 顶部卡片数据
const dataCardsData = computed(() => [
  {
    title: '用户状态',
    value: statistics.value.users?.total_users || 0,
    subTitle: `已冻结: ${statistics.value.users?.inactive_users || 0}`,
    color: '#409EFF'
  },
  {
    title: '标签统计',
    value: statistics.value.tags?.total || 0,
    subTitle: `热门: ${statistics.value.tags?.hot?.[0]?.tag || '无'}`,
    color: '#67C23A'
  },
  {
    title: '书籍统计',
    value: statistics.value.books?.total_books || 0,
    subTitle: `已下架: ${statistics.value.books?.inactive_books || 0}`,
    color: '#E6A23C'
  },
  {
    title: '举报数量',
    value: statistics.value.interactions?.total_reports || 0,
    subTitle: `待处理举报: ${statistics.value.interactions?.pending_reports || 0}`,
    color: '#F56C6C'
  }
])

// 图表实例存储
let charts = []

// 初始化热门书籍图表
const initHotBooksChart = () => {
  if (!hotBooksChartRef.value) return null

  const chart = echarts.init(hotBooksChartRef.value)
  const chartData = []

  if (Array.isArray(statistics.value.hotBooks)) {
    statistics.value.hotBooks.slice(0, 5).forEach(book => {
      if (book && book.title) {
        const value = (parseInt(book.like_count) || 0) + (parseInt(book.comment_count) || 0)
        chartData.push({
          name: book.title,
          value: value
        })
      }
    })
  }

  if (chartData.length === 0) {
    chartData.push({ name: '暂无数据', value: 0 })
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const book = statistics.value.hotBooks.find(b => b.title === params.name)
        return `${params.seriesName} <br/>
                ${params.name} <br/>
                总互动: ${params.value} (${params.percent}%) <br/>
                点赞数: ${book.like_count} <br/>
                评论数: ${book.comment_count}`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '热门书籍',
        type: 'pie',
        radius: '50%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  try {
    chart.setOption(option)
    return chart
  } catch (error) {
    console.error('初始化热门书籍图表失败:', error)
    return null
  }
}

// 初始化活跃用户图表
const initActiveUsersChart = () => {
  if (!activeUsersChartRef.value) return null

  const chart = echarts.init(activeUsersChartRef.value)
  const chartData = {
    names: [],
    posts: [],
    comments: []
  }

  if (Array.isArray(statistics.value.activeUsers)) {
    statistics.value.activeUsers.slice(0, 5).forEach(user => {
      if (user && user.nickname) {
        chartData.names.push(user.nickname)
        chartData.posts.push(parseInt(user.post_count) || 0)
        chartData.comments.push(parseInt(user.comment_count) || 0)
      }
    })
  }

  if (chartData.names.length === 0) {
    chartData.names = ['暂无数据']
    chartData.posts = [0]
    chartData.comments = [0]
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['分享数', '评论数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: { type: 'value' },
    yAxis: {
      type: 'category',
      data: chartData.names
    },
    series: [
      {
        name: '分享数',
        type: 'bar',
        data: chartData.posts
      },
      {
        name: '评论数',
        type: 'bar',
        data: chartData.comments
      }
    ]
  }

  try {
    chart.setOption(option)
    return chart
  } catch (error) {
    console.error('初始化活跃用户图表失败:', error)
    return null
  }
}

// 初始化所有图表
const initCharts = async () => {
  // 清理旧的图表实例
  charts.forEach(chart => chart?.dispose())
  charts = []

  await nextTick()
  
  const hotBooksChart = initHotBooksChart()
  if (hotBooksChart) charts.push(hotBooksChart)
  
  const activeUsersChart = initActiveUsersChart()
  if (activeUsersChart) charts.push(activeUsersChart)
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    loading.value = true
    const res = await getStatistics()
    
    if (res.code === 200 && res.data) {
      statistics.value = res.data
      dataCards.value = dataCardsData.value
      await initCharts()
    } else {
      throw new Error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 监听窗口大小变化
const resizeHandler = () => {
  charts.forEach(chart => chart?.resize())
}

onMounted(async () => {
  await fetchStatistics()
  window.addEventListener('resize', resizeHandler)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler)
  charts.forEach(chart => chart?.dispose())
  charts = []
})
</script>

<style scoped>
.data-display {
  padding: 20px;
}

.data-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.card-content {
  text-align: center;
  padding: 10px;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.card-sub-title {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
  width: 100%;
  margin: 20px 0;
}

.card-header {
  font-weight: bold;
}
</style>
